<template>
  <el-form 
    :inline="true"
    :model="queryForm"
    class="query-form"
  >
    <el-form-item 
      v-for="field in fields" 
      :key="field.fieldName"
    >
      <component 
        :is="getQueryComponent(field.queryComponentType)"
        :field="field"
        :value="queryForm[field.fieldName]"
        @input="handleFieldInput(field.fieldName, $event)"
      ></component>
    </el-form-item>
    
    <el-form-item>
      <el-button type="primary" @click="handleQuery">查询</el-button>
      <el-button @click="handleReset">重置</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import QueryText from './query/QueryText.vue'
import QuerySelect from './query/QuerySelect.vue'
import QueryDateRange from './query/QueryDateRange.vue'

// 定义组件
const components = {
  QueryText,
  QuerySelect,
  QueryDateRange
}

// 接收的参数
const props = defineProps({
  fields: {
    type: Array,
    default: () => []
  }
})

// 发出的事件
const emit = defineEmits(['query', 'reset'])

// 查询表单数据
const queryForm = ref({})

// 初始化
onMounted(() => {
  initQueryForm()
})

// 初始化查询表单
const initQueryForm = () => {
  props.fields.forEach(field => {
    queryForm.value[field.fieldName] = undefined
  })
}

// 获取查询组件
const getQueryComponent = (type) => {
  switch(type) {
    case 'text': return 'QueryText'
    case 'select': return 'QuerySelect'
    case 'date-range': return 'QueryDateRange'
    default: return 'QueryText'
  }
}

// 处理字段输入
const handleFieldInput = (fieldName, value) => {
  queryForm.value[fieldName] = value
}

// 处理查询
const handleQuery = () => {
  // 构建查询参数
  const params = []
  props.fields.forEach(field => {
    const value = queryForm.value[field.fieldName]
    if (value !== undefined && value !== null && value !== '') {
      params.push({
        fieldName: field.fieldName,
        value: value,
        queryType: field.queryType,
        fieldType: field.fieldType,
        isBaseField: field.isBaseField,
        systemFieldName: field.systemFieldName
      })
    }
  })
  emit('query', params)
}

// 处理重置
const handleReset = () => {
  initQueryForm()
  emit('reset')
}
</script>

<style scoped>
.query-form {
  margin-bottom: 20px;
  padding: 10px;
  background-color: #f9fafc;
  border-radius: 4px;
}
</style>
